package com.itheima.controller;

import cn.hutool.core.util.RandomUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.itheima.common.R;
import com.itheima.dto.MobileLoginDTO;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import com.itheima.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**用户接口
 * @author msi
 */
@RequestMapping("/user")
@RestController
@Slf4j
public class UserController {

    /**
     * 阿里云可以获取到
     */
    @Value("${reggie.keyId}")
    private String keyId;
    /**
     * 阿里云可以获取到
     */
    @Value("${reggie.secret}")
    private String secret;
    @Resource
    private UserService service;
    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    @PostMapping("/sendMsg")
    public void sendMsg(@RequestBody MobileLoginDTO mobileLoginDTO) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", keyId, secret);

        IAcsClient client = new DefaultAcsClient(profile);

        long round = Math.round((Math.random() + RandomUtil.randomInt(1,10)) * 1000);
        String code = Long.toString(round);
        String phone = mobileLoginDTO.getPhone();

        SendSmsRequest request = new SendSmsRequest();
        request.setSignName("阿里云短信测试");
        request.setTemplateCode("SMS_154950909");
        request.setPhoneNumbers(phone);
        request.setTemplateParam("{\"code\":" + code + "}");

        try {
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        redisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);
        log.info("验证码是:"+code);
    }

    @PostMapping("/login")
    public R<UserVO> login(@RequestBody MobileLoginDTO loginDTO) {
        String phone = loginDTO.getPhone();
        String code = loginDTO.getCode();
        String rightCode =(String) redisTemplate.opsForValue().get(phone);
        if (rightCode==null){
            return null;
        }
        if (rightCode.equals(code)){

            User user = service.login(phone);
            String token = UUID.randomUUID() + "";
            token = token.replace("-", "");

            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user,userVO);
            userVO.setToken(token);
            redisTemplate.delete(phone);
            redisTemplate.opsForValue().set(token,userVO,7, TimeUnit.DAYS);

            return R.success(userVO);
        }
        return null;
    }

    @PostMapping("/loginout")
    public R<String> loginOut(HttpServletRequest request){
        String token = request.getHeader("AuthorizationUser");
        redisTemplate.delete(token);

        return R.success("操作成功");
    }

}
